// src/core/storage_core.c
#include <string.h>
#include "esp_log.h"
#include "esp_vfs.h"
#include "storage.h"

static const char *TAG = "storage_core";

esp_err_t file_system_init(file_system_t *fs, const fs_config_t *config) 
{
    if (!fs || !config) {
        return ESP_ERR_INVALID_ARG;
    }
    
    esp_err_t ret = ESP_OK;  // 在开始就定义返回值

    // 复制配置
    memcpy(&fs->config, config, sizeof(fs_config_t));
    
    // 检查存储设备是否已配置
    if (!fs->config.storage_dev) {
        ESP_LOGE(TAG, "Storage device not configured");
        return ESP_ERR_INVALID_STATE;
    }

    // 初始化存储设备
    ret = fs->config.storage_dev->ops.init(&fs->config.storage_dev->config);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to initialize storage device");
        return ret;
    }

    // 配置LittleFS - 保持不变

    // 创建互斥锁
    fs->mutex = xSemaphoreCreateMutex();
    if (!fs->mutex) {
        ESP_LOGE(TAG, "Failed to create mutex");
        fs->config.storage_dev->ops.deinit();
        return ESP_ERR_NO_MEM;
    }

    // 初始化meta数据缓存
    ret = file_system_init_cache(fs);
    if (ret != ESP_OK) {
        vSemaphoreDelete(fs->mutex);
        fs->config.storage_dev->ops.deinit();
        return ret;
    }

    // 初始化DMA管理器
    ret = file_system_init_dma(fs);
    if (ret != ESP_OK) {
        file_system_deinit_cache(fs);
        vSemaphoreDelete(fs->mutex);
        fs->config.storage_dev->ops.deinit();
        return ret;
    }

    // 挂载文件系统
    esp_vfs_littlefs_conf_t littlefs_conf = {
        .base_path = fs->config.base_path,
        .partition_label = fs->config.partition_label,
        .format_if_mount_failed = fs->config.format_if_mount_failed,
        .dont_mount = false
    };
    
    ret = esp_vfs_littlefs_register(&littlefs_conf);
    if (ret != ESP_OK) {
        file_system_deinit_dma(fs);
        file_system_deinit_cache(fs);
        vSemaphoreDelete(fs->mutex);
        fs->config.storage_dev->ops.deinit();
        ESP_LOGE(TAG, "Failed to mount filesystem");
        return ret;
    }

    fs->mounted = true;

    // 初始化事务管理
    fs->transaction = calloc(1, sizeof(transaction_data_t));
    if (!fs->transaction) {
        // 清理所有已分配的资源
        esp_vfs_littlefs_unregister(fs->config.partition_label);
        file_system_deinit_dma(fs);
        file_system_deinit_cache(fs);
        vSemaphoreDelete(fs->mutex);
        fs->config.storage_dev->ops.deinit();
        fs->mounted = false;
        return ESP_ERR_NO_MEM;
    }

    // 检查是否需要断电恢复
    ret = fs_power_fail_recover(fs);
    if (ret != ESP_OK) {
        // 清理所有资源
        free(fs->transaction);
        esp_vfs_littlefs_unregister(fs->config.partition_label);
        file_system_deinit_dma(fs);
        file_system_deinit_cache(fs);
        vSemaphoreDelete(fs->mutex);
        fs->config.storage_dev->ops.deinit();
        fs->mounted = false;
        ESP_LOGE(TAG, "Failed to recover from power failure");
    }

    return ret;
}


void file_system_deinit(file_system_t *fs) {
    if (!fs || !fs->mounted) {
        return;
    }

    // 清理DMA
    file_system_deinit_dma(fs);

    // 清理缓存
    file_system_deinit_cache(fs);

    // 清理存储设备
    if (fs->config.storage_dev) {
        fs->config.storage_dev->ops.flush();
        fs->config.storage_dev->ops.deinit();
    }

    // 卸载文件系统
    esp_vfs_littlefs_unregister(fs->config.partition_label);
    fs->mounted = false;

    // 删除互斥锁
    if (fs->mutex) {
        vSemaphoreDelete(fs->mutex);
        fs->mutex = NULL;
    }

    ESP_LOGI(TAG, "Filesystem deinitialized");
}


esp_err_t file_system_stat(file_system_t *fs, const char *path, struct stat *st) {
    if (!fs || !fs->mounted || !path || !st) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);

    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    int ret = stat(full_path, st);
    
    xSemaphoreGive(fs->mutex);

    if (ret != 0) {
        ESP_LOGE(TAG, "Failed to get file stats: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    return ESP_OK;
}


esp_err_t file_system_format(file_system_t *fs) {
    if (!fs || !fs->mounted) {
        return ESP_ERR_INVALID_ARG;
    }

    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    esp_err_t ret = esp_littlefs_format(fs->config.partition_label);
    
    xSemaphoreGive(fs->mutex);

    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to format filesystem");
        return ret;
    }

    ESP_LOGI(TAG, "Filesystem formatted successfully");
    return ESP_OK;
}


esp_err_t file_system_exists(file_system_t *fs, const char *path, bool *exists) 
{
    if (!fs || !fs->mounted || !path || !exists) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);

    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    struct stat st;
    int ret = stat(full_path, &st);
    
    xSemaphoreGive(fs->mutex);

    *exists = (ret == 0);
    
    ESP_LOGV(TAG, "Path %s %s", full_path, *exists ? "exists" : "does not exist");
    return ESP_OK;
}


// src/core/storage_ops.c
#include "esp_log.h"
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include "storage.h"

static const char *TAG = "storage_ops";


esp_err_t file_system_read(file_system_t *fs, const char *path, void *data, size_t size, size_t *read_size) {
    esp_err_t ret = ESP_OK;
    FILE *file = NULL;
    
    // 参数验证
    if (!fs || !fs->mounted || !path || !data || !read_size) {
        return ESP_ERR_INVALID_ARG;
    }
    
    char full_path[FILE_PATH_MAX] = {0};
    if (snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path) >= sizeof(full_path)) {
        return ESP_ERR_INVALID_SIZE;
    }

    // 开始时间统计
    uint64_t start_time = esp_timer_get_time();
    bool cache_hit = false;
    
    // 获取互斥锁
    if (xSemaphoreTake(fs->mutex, portMAX_DELAY) != pdTRUE) {
        ESP_LOGE(TAG, "Failed to take mutex for reading %s", full_path);
        return ESP_ERR_TIMEOUT;
    }
    
    do {
        // 检查缓存
        fs_cache_entry_t *cache_entry = find_cache_entry(fs, path);
        if (cache_entry) {
            cache_hit = true;
            *read_size = (size < cache_entry->size) ? size : cache_entry->size;
            memcpy(data, cache_entry->data, *read_size);
            cache_entry->last_access = time(NULL);
            break;
        }
        
        // 打开文件
        file = fopen(full_path, "rb");
        if (!file) {
            ESP_LOGE(TAG, "Failed to open file: %s (errno: %d)", full_path, errno);
            ret = ESP_FAIL;
            break;
        }
        
        // 读取文件
        *read_size = fread(data, 1, size, file);
        if (*read_size == 0 && !feof(file)) {
            ESP_LOGE(TAG, "Failed to read file: %s (errno: %d)", full_path, errno);
            ret = ESP_FAIL;
            break;
        }
        
        // 更新缓存
        if ((ret = add_to_cache(fs, path, data, *read_size)) != ESP_OK) {
            ESP_LOGW(TAG, "Failed to cache file: %s", full_path);
        }
        
    } while (0);
    
    // 清理资源
    if (file) {
        fclose(file);
    }

    // 结束时间统计
    uint64_t end_time = esp_timer_get_time();
    if (fs->cache) {
        if (cache_hit) {
            fs->cache->stats.cache_hits++;
        } else {
            fs->cache->stats.cache_misses++;
        }
        fs->cache->stats.total_read_time += (end_time - start_time);
    }
    
    xSemaphoreGive(fs->mutex);
    return ret;
}


esp_err_t file_system_write(file_system_t *fs, const char *path, const void *data, size_t size) {
    if (!fs || !fs->mounted || !path || (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    char full_path[FILE_PATH_MAX] = {0};

    if (snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path) >= sizeof(full_path)) {
        return ESP_ERR_INVALID_SIZE;
    }

    uint64_t start_time = esp_timer_get_time();
    
    if (xSemaphoreTake(fs->mutex, portMAX_DELAY) != pdTRUE) {
        return ESP_ERR_TIMEOUT;
    }

    // 检查和更新缓存
    fs_cache_entry_t *cache_entry = find_cache_entry(fs, path);
    if (cache_entry) {
        // 验证缓存数据完整性
        if (cache_entry->data == NULL) {
            remove_cache_entry(fs, cache_entry);
            cache_entry = NULL;
        } else {
            // 更新缓存
            if (size > cache_entry->capacity) {
                uint8_t *new_data = realloc(cache_entry->data, size);
                if (!new_data) {
                    xSemaphoreGive(fs->mutex);
                    return ESP_ERR_NO_MEM;
                }
                cache_entry->data = new_data;
                cache_entry->capacity = size;
            }
            memcpy(cache_entry->data, data, size);
            cache_entry->size = size;
            cache_entry->dirty = true;
            cache_entry->last_access = time(NULL);
        }
    }

    // 使用存储设备接口写入
    ret = fs->config.storage_dev->ops.write(data, size);
    if (ret != ESP_OK) {
        if (cache_entry) {
            cache_entry->dirty = false; // 写入失败，标记缓存为无效
        }
        xSemaphoreGive(fs->mutex);
        return ret;
    }

    // 如果缓存未命中且写入成功，添加到缓存
    if (!cache_entry) {
        ret = add_to_cache(fs, path, data, size);
        // 添加缓存失败不影响写入结果
        if (ret != ESP_OK) {
            ESP_LOGW(TAG, "Failed to cache file: %s", full_path);
        }
    }

    // 更新写入时间统计
    if (fs->cache) {
        uint64_t end_time = esp_timer_get_time();
        fs->cache->stats.total_write_time += (end_time - start_time);
    }
    
    xSemaphoreGive(fs->mutex);
    return ESP_OK;
}


esp_err_t file_system_append(file_system_t *fs, const char *path, const void *data, size_t size) {
    if (!fs || !fs->mounted || !path || (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    char full_path[FILE_PATH_MAX] = {0};

    // 构建完整路径
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);

    xSemaphoreTake(fs->mutex, portMAX_DELAY);

    // 打开文件用于追加
    FILE *file = fopen(full_path, "ab");
    if (!file) {
        ESP_LOGE(TAG, "Failed to open file for appending: %s (errno: %d)", full_path, errno);
        xSemaphoreGive(fs->mutex);
        return ESP_FAIL;
    }

    // 写入数据
    size_t written = fwrite(data, 1, size, file);
    if (written != size) {
        ESP_LOGE(TAG, "Failed to append to file: %s (written: %zu, expected: %zu)", 
                 full_path, written, size);
        ret = ESP_FAIL;
    }

    fclose(file);
    xSemaphoreGive(fs->mutex);

    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "Successfully appended %zu bytes to %s", size, full_path);
    }

    return ret;
}


esp_err_t file_system_remove(file_system_t *fs, const char *path) {
    if (!fs || !fs->mounted || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);

    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    int ret = remove(full_path);
    
    xSemaphoreGive(fs->mutex);

    if (ret != 0) {
        ESP_LOGE(TAG, "Failed to remove file: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    ESP_LOGI(TAG, "Successfully removed %s", full_path);
    return ESP_OK;
}


esp_err_t file_system_rename(file_system_t *fs, const char *old_path, const char *new_path) {
    if (!fs || !fs->mounted || !old_path || !new_path) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_old_path[FILE_PATH_MAX] = {0};
    char full_new_path[FILE_PATH_MAX] = {0};
    
    snprintf(full_old_path, sizeof(full_old_path), "%s%s", fs->config.base_path, old_path);
    snprintf(full_new_path, sizeof(full_new_path), "%s%s", fs->config.base_path, new_path);

    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    int ret = rename(full_old_path, full_new_path);
    
    xSemaphoreGive(fs->mutex);

    if (ret != 0) {
        ESP_LOGE(TAG, "Failed to rename file from %s to %s (errno: %d)", 
                 full_old_path, full_new_path, errno);
        return ESP_FAIL;
    }

    ESP_LOGI(TAG, "Successfully renamed %s to %s", full_old_path, full_new_path);
    return ESP_OK;
}


esp_err_t file_system_mkdir(file_system_t *fs, const char *path) {
    if (!fs || !fs->mounted || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);

    xSemaphoreTake(fs->mutex, portMAX_DELAY);

    int ret = mkdir(full_path, 0755);  // 0755是标准的目录权限

    xSemaphoreGive(fs->mutex);

    if (ret != 0) {
        ESP_LOGE(TAG, "Failed to create directory: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    ESP_LOGI(TAG, "Successfully created directory: %s", full_path);
    return ESP_OK;
}


esp_err_t file_system_rmdir(file_system_t *fs, const char *path) {
    if (!fs || !fs->mounted || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);

    xSemaphoreTake(fs->mutex, portMAX_DELAY);

    int ret = rmdir(full_path);

    xSemaphoreGive(fs->mutex);

    if (ret != 0) {
        ESP_LOGE(TAG, "Failed to remove directory: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    ESP_LOGI(TAG, "Successfully removed directory: %s", full_path);
    return ESP_OK;
}


esp_err_t file_system_list_directory(file_system_t *fs, const char *path, file_info_t *files, size_t *count) {
    if (!fs || !fs->mounted || !path || !files || !count || *count == 0) {
        return ESP_ERR_INVALID_ARG; 
    }

    char full_path[FILE_PATH_MAX] = {0};
    if (snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path) >= sizeof(full_path)) {
        return ESP_ERR_INVALID_SIZE;
    }

    xSemaphoreTake(fs->mutex, portMAX_DELAY);

    DIR *dir = opendir(full_path);
    if (!dir) {
        xSemaphoreGive(fs->mutex);
        ESP_LOGE(TAG, "Failed to open directory: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    size_t index = 0;
    const size_t max_count = *count; // 保存最大数量限制
    struct dirent *entry;
    struct stat st;

    while ((entry = readdir(dir)) != NULL && index < max_count) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        char file_path[FILE_PATH_MAX];
        if (snprintf(file_path, sizeof(file_path), "%s/%s", full_path, entry->d_name) >= sizeof(file_path)) {
            continue; // 跳过路径过长的文件
        }

        if (stat(file_path, &st) == 0) {
            strncpy(files[index].name, entry->d_name, FILE_NAME_MAX - 1);
            files[index].name[FILE_NAME_MAX - 1] = '\0'; // 确保字符串终止
            files[index].size = st.st_size;
            files[index].is_directory = S_ISDIR(st.st_mode);
            files[index].modified_time = st.st_mtime;
            index++;
        }
    }

    closedir(dir);
    xSemaphoreGive(fs->mutex);

    *count = index;
    ESP_LOGI(TAG, "Listed %zu files in %s", index, full_path);
    return ESP_OK;
}

#include "esp_log.h"
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include "esp_mac.h"
#include "esp_vfs.h"
#include "storage.h"


esp_err_t file_system_init_cache(file_system_t *fs) 
{
    fs->cache = calloc(1, sizeof(fs_cache_t));
    if (!fs->cache) {
        return ESP_ERR_NO_MEM;
    }
    
    fs->cache->entries = calloc(MAX_CACHE_ENTRIES, sizeof(fs_cache_entry_t));
    if (!fs->cache->entries) {
        free(fs->cache);
        return ESP_ERR_NO_MEM;
    }
    
    fs->cache->capacity = MAX_CACHE_ENTRIES;
    fs->cache->max_cache_size = MAX_CACHE_SIZE;
    return ESP_OK;
}


fs_cache_entry_t* find_cache_entry(file_system_t *fs, const char *path) {
    for (size_t i = 0; i < fs->cache->count; i++) {
        if (strcmp(fs->cache->entries[i].path, path) == 0) {
            fs->cache->entries[i].last_access = time(NULL);
            return &fs->cache->entries[i];
        }
    }
    return NULL;
}


static esp_err_t flush_cache_entry(file_system_t *fs, fs_cache_entry_t *entry) {
    if (!entry->dirty) {
        return ESP_OK;
    }

    esp_err_t ret = file_system_write(fs, entry->path, entry->data, entry->size);
    if (ret == ESP_OK) {
        entry->dirty = false;
        if (fs->cache) {
            fs->cache->stats.buffer_flushes++;
        }
    }
    return ret;
}


void file_system_flush_cache(file_system_t *fs) {
    if (!fs->cache) {
        return;
    }
    
    for (size_t i = 0; i < fs->cache->count; i++) {
        flush_cache_entry(fs, &fs->cache->entries[i]);
        free(fs->cache->entries[i].path);
        free(fs->cache->entries[i].data);
    }
    
    fs->cache->count = 0;
}


void file_system_deinit_cache(file_system_t *fs) {
    if (!fs->cache) {
        return;
    }
    
    file_system_flush_cache(fs);
    free(fs->cache->entries);
    free(fs->cache);
    fs->cache = NULL;
}


void evict_cache_entry(file_system_t *fs) {
    if (fs->cache->count == 0) return;
    
    size_t oldest_idx = 0;
    time_t oldest_time = fs->cache->entries[0].last_access;
    
    for (size_t i = 1; i < fs->cache->count; i++) {
        if (fs->cache->entries[i].last_access < oldest_time) {
            oldest_idx = i;
            oldest_time = fs->cache->entries[i].last_access;
        }
    }
    
    flush_cache_entry(fs, &fs->cache->entries[oldest_idx]);
    free(fs->cache->entries[oldest_idx].path);
    free(fs->cache->entries[oldest_idx].data);
    
    if (oldest_idx < fs->cache->count - 1) {
        memmove(&fs->cache->entries[oldest_idx], 
                &fs->cache->entries[oldest_idx + 1],
                (fs->cache->count - oldest_idx - 1) * sizeof(fs_cache_entry_t));
    }
    fs->cache->count--;
}


esp_err_t add_to_cache(file_system_t *fs, const char *path, const uint8_t *data, size_t size) {
    while (fs->cache->count >= fs->cache->capacity || 
           size > fs->cache->max_cache_size) {
        evict_cache_entry(fs);
    }
    
    fs_cache_entry_t *entry = &fs->cache->entries[fs->cache->count];
    entry->path = strdup(path);
    entry->data = malloc(size);
    
    if (!entry->path || !entry->data) {
        free(entry->path);
        free(entry->data);
        return ESP_ERR_NO_MEM;
    }
    
    memcpy(entry->data, data, size);
    entry->size = size;
    entry->capacity = size;
    entry->dirty = false;
    entry->last_access = time(NULL);
    fs->cache->count++;
    
    return ESP_OK;
}


#include <string.h>
#include "esp_log.h"
#include "esp_heap_caps.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "storage.h"

static const char *TAG = "storage_dma";

// 实现 DMA 初始化
esp_err_t file_system_init_dma(file_system_t *fs) {
    if (!fs) {
        return ESP_ERR_INVALID_ARG;
    }

    fs->dma_mgr = calloc(1, sizeof(dma_manager_t));
    if (!fs->dma_mgr) {
        return ESP_ERR_NO_MEM;
    }

    // 初始化缓冲区切换互斥锁
    fs->dma_mgr->buffer_switch_mutex = xSemaphoreCreateMutex();
    if (!fs->dma_mgr->buffer_switch_mutex) {
        free(fs->dma_mgr);
        return ESP_ERR_NO_MEM;
    }

    // 初始化DMA缓冲区
    for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
        fs->dma_mgr->buffers[i].buffer = heap_caps_malloc(DMA_BUFFER_SIZE, MALLOC_CAP_DMA);
        if (!fs->dma_mgr->buffers[i].buffer) {
            file_system_deinit_dma(fs);
            return ESP_ERR_NO_MEM;
        }
        
        fs->dma_mgr->buffers[i].size = DMA_BUFFER_SIZE;
        fs->dma_mgr->buffers[i].in_use = false;
        fs->dma_mgr->buffers[i].mutex = xSemaphoreCreateMutex();
        
        if (!fs->dma_mgr->buffers[i].mutex) {
            file_system_deinit_dma(fs);
            return ESP_ERR_NO_MEM;
        }
    }

    fs->dma_mgr->current_write_buffer = 0;
    fs->dma_mgr->current_read_buffer = 0;

    return ESP_OK;
}


// 实现 DMA 清理
esp_err_t file_system_deinit_dma(file_system_t *fs) {
    if (!fs || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
        if (fs->dma_mgr->buffers[i].buffer) {
            heap_caps_free(fs->dma_mgr->buffers[i].buffer);
        }
        if (fs->dma_mgr->buffers[i].mutex) {
            vSemaphoreDelete(fs->dma_mgr->buffers[i].mutex);
        }
    }

    if (fs->dma_mgr->buffer_switch_mutex) {
        vSemaphoreDelete(fs->dma_mgr->buffer_switch_mutex);
    }

    free(fs->dma_mgr);
    fs->dma_mgr = NULL;

    return ESP_OK;
}


// DMA写入实现
esp_err_t file_system_write_dma(file_system_t *fs, const char *path, 
                               size_t (*data_cb)(void*, size_t, void*), void *user_data) {
    if (!fs || !fs->mounted || !path || !data_cb || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    if (snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path) >= sizeof(full_path)) {
        return ESP_ERR_INVALID_SIZE;
    }

    FILE *file = fopen(full_path, "wb");
    if (!file) {
        ESP_LOGE(TAG, "Failed to open file for writing: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    esp_err_t ret = ESP_OK;
    bool continue_writing = true;

    while (continue_writing) {
        // 获取当前写入缓冲区
        xSemaphoreTake(fs->dma_mgr->buffer_switch_mutex, portMAX_DELAY);
        dma_buffer_t *current_buffer = &fs->dma_mgr->buffers[fs->dma_mgr->current_write_buffer];
        xSemaphoreGive(fs->dma_mgr->buffer_switch_mutex);
        
        if (xSemaphoreTake(current_buffer->mutex, portMAX_DELAY) != pdTRUE) {
            ret = ESP_FAIL;
            break;
        }

        // 从回调获取数据
        size_t data_size = data_cb(current_buffer->buffer, current_buffer->size, user_data);
        if (data_size == 0) {
            xSemaphoreGive(current_buffer->mutex);
            continue_writing = false;
            continue;
        }

        // 验证DMA传输完成
        if (fs->dma_mgr->optimization_ctx) {
            ret = dma_wait_complete(fs, pdMS_TO_TICKS(DMA_TIMEOUT_MS));
            if (ret != ESP_OK) {
                xSemaphoreGive(current_buffer->mutex);
                break;
            }
        }

        // 写入文件
        size_t written = fwrite(current_buffer->buffer, 1, data_size, file);
        if (written != data_size) {
            ESP_LOGE(TAG, "Failed to write to file: %s (errno: %d)", full_path, errno);
            ret = ESP_FAIL;
            xSemaphoreGive(current_buffer->mutex);
            break;
        }

        xSemaphoreGive(current_buffer->mutex);

        // 切换到下一个缓冲区
        xSemaphoreTake(fs->dma_mgr->buffer_switch_mutex, portMAX_DELAY);
        fs->dma_mgr->current_write_buffer = (fs->dma_mgr->current_write_buffer + 1) % NUM_DMA_BUFFERS;
        xSemaphoreGive(fs->dma_mgr->buffer_switch_mutex);
    }

    fclose(file);
    
    if (ret != ESP_OK) {
        // 写入失败时删除文件
        remove(full_path);
    }
    
    return ret;
}


// DMA读取实现
esp_err_t file_system_read_dma(file_system_t *fs, const char *path, 
                              bool (*process_cb)(const void*, size_t, void*), void *user_data) {
    if (!fs || !fs->mounted || !path || !process_cb || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    if (snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path) >= sizeof(full_path)) {
        return ESP_ERR_INVALID_SIZE;
    }

    FILE *file = fopen(full_path, "rb");
    if (!file) {
        ESP_LOGE(TAG, "Failed to open file for reading: %s (errno: %d)", full_path, errno);
        return ESP_FAIL;
    }

    esp_err_t ret = ESP_OK;
    bool continue_reading = true;

    while (continue_reading) {
        // 获取当前读取缓冲区
        xSemaphoreTake(fs->dma_mgr->buffer_switch_mutex, portMAX_DELAY);
        dma_buffer_t *current_buffer = &fs->dma_mgr->buffers[fs->dma_mgr->current_read_buffer];
        xSemaphoreGive(fs->dma_mgr->buffer_switch_mutex);
        
        if (xSemaphoreTake(current_buffer->mutex, portMAX_DELAY) != pdTRUE) {
            ret = ESP_FAIL;
            break;
        }

        // 读取数据到缓冲区
        size_t read_size = fread(current_buffer->buffer, 1, current_buffer->size, file);
        if (read_size == 0) {
            if (feof(file)) {
                xSemaphoreGive(current_buffer->mutex);
                break;
            }
            ESP_LOGE(TAG, "Failed to read from file: %s (errno: %d)", full_path, errno);
            ret = ESP_FAIL;
            xSemaphoreGive(current_buffer->mutex);
            break;
        }

        // 验证DMA传输完成
        if (fs->dma_mgr->optimization_ctx) {
            ret = dma_wait_complete(fs, pdMS_TO_TICKS(DMA_TIMEOUT_MS));
            if (ret != ESP_OK) {
                xSemaphoreGive(current_buffer->mutex);
                break;
            }
        }

        // 处理数据
        bool should_continue = process_cb(current_buffer->buffer, read_size, user_data);
        xSemaphoreGive(current_buffer->mutex);

        if (!should_continue) {
            break;
        }

        // 切换到下一个缓冲区
        xSemaphoreTake(fs->dma_mgr->buffer_switch_mutex, portMAX_DELAY);
        fs->dma_mgr->current_read_buffer = (fs->dma_mgr->current_read_buffer + 1) % NUM_DMA_BUFFERS;
        xSemaphoreGive(fs->dma_mgr->buffer_switch_mutex);
    }

    fclose(file);
    return ret;
}


#include <string.h>
#include "esp_log.h"
#include "esp_heap_caps.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "storage.h"

static const char *TAG = "storage_dma_opt";

#define DMA_TRANSFER_COMPLETE_BIT (1 << 0)

// DMA传输优化配置结构
typedef struct {
    dma_transfer_mode_t mode;
    dma_descriptor_t *desc_chain;
    size_t desc_count;
    EventGroupHandle_t events;
    bool transfer_active;
} dma_opt_context_t;


// DMA优化上下文初始化
static dma_opt_context_t* dma_opt_init(file_system_t *fs) {
    if (!fs->dma_mgr) {
        return NULL;
    }

    dma_opt_context_t *ctx = calloc(1, sizeof(dma_opt_context_t));
    if (!ctx) {
        return NULL;
    }

    ctx->events = xEventGroupCreate();
    if (!ctx->events) {
        free(ctx);
        return NULL;
    }

    return ctx;
}


// 优化DMA传输设置
esp_err_t dma_optimize_transfer(file_system_t *fs, dma_transfer_mode_t mode) {
    if (!fs || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    // 释放旧的optimization context
    if (fs->dma_mgr->optimization_ctx) {
        dma_opt_context_t *old_ctx = fs->dma_mgr->optimization_ctx;
        if (old_ctx->desc_chain) {
            free(old_ctx->desc_chain);
        }
        if (old_ctx->events) {
            vEventGroupDelete(old_ctx->events);
        }
        free(old_ctx);
    }

    dma_opt_context_t *ctx = dma_opt_init(fs);
    if (!ctx) {
        return ESP_ERR_NO_MEM;
    }

    ctx->mode = mode;
    
    // 根据传输模式优化DMA设置
    switch (mode) {
        case DMA_MODE_SINGLE:
            // 配置单次传输优化参数
            for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
                uint8_t *old_buf = fs->dma_mgr->buffers[i].buffer;
                if (fs->dma_mgr->buffers[i].size != DMA_OPTIMAL_BLOCK_SIZE) {
                    uint8_t *new_buf = heap_caps_realloc(NULL,
                                                     DMA_OPTIMAL_BLOCK_SIZE,
                                                     MALLOC_CAP_DMA);
                    if (!new_buf) {
                        free(ctx);
                        return ESP_ERR_NO_MEM;
                    }
                    heap_caps_free(old_buf);
                    fs->dma_mgr->buffers[i].buffer = new_buf;
                    fs->dma_mgr->buffers[i].size = DMA_OPTIMAL_BLOCK_SIZE;
                }
            }
            break;

        case DMA_MODE_SCATTER:
        case DMA_MODE_GATHER: {
            size_t optimal_size = DMA_OPTIMAL_BLOCK_SIZE / DMA_MAX_SCATTER_GATHER;
            // 配置分散/聚集传输的缓冲区
            for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
                uint8_t *old_buf = fs->dma_mgr->buffers[i].buffer;
                uint8_t *new_buf = heap_caps_realloc(NULL,
                                                 optimal_size,
                                                 MALLOC_CAP_DMA);
                if (!new_buf) {
                    free(ctx);
                    return ESP_ERR_NO_MEM;
                }
                heap_caps_free(old_buf);
                fs->dma_mgr->buffers[i].buffer = new_buf;
                fs->dma_mgr->buffers[i].size = optimal_size;
            }
            break;
        }

        case DMA_MODE_CIRCULAR:
            // 配置循环传输模式
            for (int i = 0; i < NUM_DMA_BUFFERS; i++) {
                uint8_t *old_buf = fs->dma_mgr->buffers[i].buffer;
                uint8_t *new_buf = heap_caps_realloc(NULL,
                                                 DMA_PREFETCH_SIZE,
                                                 MALLOC_CAP_DMA);
                if (!new_buf) {
                    free(ctx);
                    return ESP_ERR_NO_MEM;
                }
                heap_caps_free(old_buf);
                fs->dma_mgr->buffers[i].buffer = new_buf;
                fs->dma_mgr->buffers[i].size = DMA_PREFETCH_SIZE;
            }
            break;

        default:
            free(ctx);
            return ESP_ERR_INVALID_ARG;
    }

    // 存储优化上下文
    fs->dma_mgr->optimization_ctx = ctx;
    return ESP_OK;
}


// 设置DMA描述符链
esp_err_t dma_set_descriptor_chain(file_system_t *fs, dma_descriptor_t *desc, size_t count) {
    if (!fs || !fs->dma_mgr || !desc || count == 0) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_opt_context_t *ctx = fs->dma_mgr->optimization_ctx;
    if (!ctx) {
        return ESP_ERR_INVALID_STATE;
    }

    // 验证描述符链
    size_t total_size = 0;
    for (size_t i = 0; i < count; i++) {
        if (!desc[i].buf || desc[i].size == 0) {
            return ESP_ERR_INVALID_ARG;
        }
        total_size += desc[i].size;
    }

    // 检查是否超过最大传输限制
    if (total_size > DMA_PREFETCH_SIZE * NUM_DMA_BUFFERS) {
        return ESP_ERR_INVALID_SIZE;
    }

    // 保存描述符链信息
    ctx->desc_chain = malloc(count * sizeof(dma_descriptor_t));
    if (!ctx->desc_chain) {
        return ESP_ERR_NO_MEM;
    }
    memcpy(ctx->desc_chain, desc, count * sizeof(dma_descriptor_t));
    ctx->desc_count = count;

    return ESP_OK;
}


// 启动DMA传输
esp_err_t dma_start_transfer(file_system_t *fs) {
    if (!fs || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_opt_context_t *ctx = fs->dma_mgr->optimization_ctx;
    if (!ctx || ctx->transfer_active || !ctx->desc_chain) {
        return ESP_ERR_INVALID_STATE;
    }

    esp_err_t ret = ESP_OK;

    // 清除传输完成标志
    xEventGroupClearBits(ctx->events, DMA_TRANSFER_COMPLETE_BIT);
    
    // 获取存储设备DMA配置
    storage_dev_dma_config_t *dma_config = &fs->config.storage_dev->dma_config;

    // 根据传输模式启动相应的传输过程
    switch (ctx->mode) {
        case DMA_MODE_SINGLE:
            ret = dma_config->start_single_transfer(ctx->desc_chain);
            break;
            
        case DMA_MODE_SCATTER:
            ret = dma_config->start_scatter_transfer(ctx->desc_chain, ctx->desc_count);
            break;
            
        case DMA_MODE_GATHER:
            ret = dma_config->start_gather_transfer(ctx->desc_chain, ctx->desc_count);
            break;
            
        case DMA_MODE_CIRCULAR:
            ret = dma_config->start_circular_transfer(ctx->desc_chain, ctx->desc_count);
            break;
            
        default:
            ret = ESP_ERR_INVALID_ARG;
            break;
    }

    if (ret == ESP_OK) {
        ctx->transfer_active = true;
    }

    return ret;
}


// 等待DMA传输完成
esp_err_t dma_wait_complete(file_system_t *fs, TickType_t timeout) {
    if (!fs || !fs->dma_mgr) {
        return ESP_ERR_INVALID_ARG;
    }

    dma_opt_context_t *ctx = fs->dma_mgr->optimization_ctx;
    if (!ctx || !ctx->transfer_active) {
        return ESP_ERR_INVALID_STATE;
    }

    // 等待传输完成事件
    EventBits_t bits = xEventGroupWaitBits(ctx->events,
                                          DMA_TRANSFER_COMPLETE_BIT,
                                          pdTRUE,
                                          pdTRUE,
                                          timeout);

    if ((bits & DMA_TRANSFER_COMPLETE_BIT) == 0) {
        return ESP_ERR_TIMEOUT;
    }

    ctx->transfer_active = false;
    return ESP_OK;
}


// src/components/protection/storage_protection.c
#include <string.h>
#include "esp_log.h"
#include "storage_protection.h"

static const char *TAG = "storage_protection";

// 初始化数据保护
esp_err_t fs_protection_init(file_system_t *fs) {
    if (!fs) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_protection_t *protection = calloc(1, sizeof(fs_protection_t));
    if (!protection) {
        return ESP_ERR_NO_MEM;
    }

    // 创建互斥锁
    protection->protection_mutex = xSemaphoreCreateMutex();
    if (!protection->protection_mutex) {
        free(protection);
        return ESP_ERR_NO_MEM;
    }

    // 分配元数据内存
    protection->metadata = calloc(1, sizeof(protection_metadata_t));
    if (!protection->metadata) {
        vSemaphoreDelete(protection->protection_mutex);
        free(protection);
        return ESP_ERR_NO_MEM;
    }

    // 初始化journal路径
    snprintf(protection->journal_path, sizeof(protection->journal_path),
             "%s/.journal", fs->config.base_path);

    // 存储保护上下文
    fs->protection = protection;
    
    ESP_LOGI(TAG, "Data protection initialized");
    return ESP_OK;
}

// 清理数据保护资源
void fs_protection_deinit(file_system_t *fs) {
    if (!fs || !fs->protection) {
        return;
    }

    if (fs->protection->protection_mutex) {
        vSemaphoreDelete(fs->protection->protection_mutex);
    }

    if (fs->protection->metadata) {
        free(fs->protection->metadata);
    }

    free(fs->protection);
    fs->protection = NULL;
}

// 计算CRC32校验值
esp_err_t fs_calc_crc32(const void *data, size_t size, uint32_t *crc) {
    if (!data || !crc || size == 0) {
        return ESP_ERR_INVALID_ARG;
    }

    // 使用ESP32硬件CRC32单元
    *crc = esp_crc32_be(CRC32_INITIAL_VALUE, data, size);
    return ESP_OK;
}

// 验证CRC32校验值
esp_err_t fs_verify_crc32(const void *data, size_t size, uint32_t expected_crc) {
    uint32_t calculated_crc;
    esp_err_t ret = fs_calc_crc32(data, size, &calculated_crc);
    if (ret != ESP_OK) {
        return ret;
    }

    return (calculated_crc == expected_crc) ? ESP_OK : ESP_FAIL;
}

// 写入带保护的数据
esp_err_t fs_write_protected(file_system_t *fs, const char *path, const void *data, size_t size) {
    if (!fs || !fs->protection || !path || (!data && size > 0)) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    fs_protection_t *protection = fs->protection;

    xSemaphoreTake(protection->protection_mutex, portMAX_DELAY);

    do {
        // 准备元数据
        protection->metadata->magic = PROTECTION_MAGIC_NUMBER;
        protection->metadata->sequence++;
        protection->metadata->data_size = size;
        protection->metadata->timestamp = time(NULL);

        // 计算数据CRC
        ret = fs_calc_crc32(data, size, &protection->metadata->crc32);
        if (ret != ESP_OK) {
            break;
        }

        // 首先写入journal
        FILE *journal = fopen(protection->journal_path, "wb");
        if (!journal) {
            ret = ESP_FAIL;
            break;
        }

        // 写入元数据
        if (fwrite(protection->metadata, sizeof(protection_metadata_t), 1, journal) != 1) {
            fclose(journal);
            ret = ESP_FAIL;
            break;
        }

        // 写入实际数据
        if (fwrite(data, 1, size, journal) != size) {
            fclose(journal);
            ret = ESP_FAIL;
            break;
        }

        fclose(journal);

        // 写入实际文件
        ret = file_system_write(fs, path, data, size);

    } while (0);

    xSemaphoreGive(protection->protection_mutex);
    return ret;
}

// 读取带保护的数据
esp_err_t fs_read_protected(file_system_t *fs, const char *path,
                           void *data, size_t size, size_t *read_size) {
    if (!fs || !fs->protection || !path || !data || !read_size) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    fs_protection_t *protection = fs->protection;

    xSemaphoreTake(protection->protection_mutex, portMAX_DELAY);

    do {
        // 读取文件数据
        ret = file_system_read(fs, path, data, size, read_size);
        if (ret != ESP_OK) {
            break;
        }

        // 验证CRC
        uint32_t calculated_crc;
        ret = fs_calc_crc32(data, *read_size, &calculated_crc);
        if (ret != ESP_OK) {
            break;
        }

        // 检查journal是否存在
        FILE *journal = fopen(protection->journal_path, "rb");
        if (journal) {
            protection_metadata_t journal_metadata;
            
            // 读取journal元数据
            if (fread(&journal_metadata, sizeof(protection_metadata_t), 1, journal) == 1) {
                if (journal_metadata.magic == PROTECTION_MAGIC_NUMBER &&
                    journal_metadata.crc32 != calculated_crc) {
                    // CRC不匹配，从journal恢复
                    void *journal_data = malloc(journal_metadata.data_size);
                    if (journal_data) {
                        if (fread(journal_data, 1, journal_metadata.data_size, journal) 
                            == journal_metadata.data_size) {
                            // 验证journal数据的CRC
                            uint32_t journal_crc;
                            if (fs_calc_crc32(journal_data, journal_metadata.data_size, &journal_crc) 
                                == ESP_OK &&
                                journal_crc == journal_metadata.crc32) {
                                // 从journal恢复数据
                                size_t copy_size = (journal_metadata.data_size < size) ? 
                                                  journal_metadata.data_size : size;
                                memcpy(data, journal_data, copy_size);
                                *read_size = copy_size;
                                calculated_crc = journal_crc;
                            }
                        }
                        free(journal_data);
                    }
                }
            }
            fclose(journal);
        }

        // 最终CRC校验
        if (fs_verify_crc32(data, *read_size, calculated_crc) != ESP_OK) {
            ret = ESP_FAIL;
            break;
        }

    } while (0);

    xSemaphoreGive(protection->protection_mutex);
    return ret;
}

// 文件系统一致性检查
esp_err_t fs_check_consistency(file_system_t *fs) {
    if (!fs || !fs->protection) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    fs_protection_t *protection = fs->protection;

    xSemaphoreTake(protection->protection_mutex, portMAX_DELAY);

    do {
        // 检查journal是否存在
        FILE *journal = fopen(protection->journal_path, "rb");
        if (!journal) {
            break;  // 无journal文件，认为是一致的
        }

        protection_metadata_t journal_metadata;
        if (fread(&journal_metadata, sizeof(protection_metadata_t), 1, journal) != 1) {
            ret = ESP_FAIL;
            fclose(journal);
            break;
        }

        // 检查magic number
        if (journal_metadata.magic != PROTECTION_MAGIC_NUMBER) {
            ret = ESP_FAIL;
            fclose(journal);
            break;
        }

        // TODO: 进一步的一致性检查，如检查所有文件的CRC等

        fclose(journal);
    } while (0);

    xSemaphoreGive(protection->protection_mutex);
    return ret;
}

// 恢复文件系统一致性
esp_err_t fs_recover_consistency(file_system_t *fs) {
    if (!fs || !fs->protection) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;
    fs_protection_t *protection = fs->protection;

    xSemaphoreTake(protection->protection_mutex, portMAX_DELAY);

    do {
        FILE *journal = fopen(protection->journal_path, "rb");
        if (!journal) {
            break;
        }

        protection_metadata_t journal_metadata;
        if (fread(&journal_metadata, sizeof(protection_metadata_t), 1, journal) != 1) {
            fclose(journal);
            ret = ESP_FAIL;
            break;
        }

        // 验证journal
        if (journal_metadata.magic != PROTECTION_MAGIC_NUMBER) {
            fclose(journal);
            ret = ESP_FAIL;
            break;
        }

        // 读取journal数据并应用恢复
        void *journal_data = malloc(journal_metadata.data_size);
        if (!journal_data) {
            fclose(journal);
            ret = ESP_ERR_NO_MEM;
            break;
        }

        if (fread(journal_data, 1, journal_metadata.data_size, journal) 
            == journal_metadata.data_size) {
            // 验证数据CRC
            uint32_t crc;
            if (fs_calc_crc32(journal_data, journal_metadata.data_size, &crc) == ESP_OK &&
                crc == journal_metadata.crc32) {
                // 应用恢复操作
                // TODO: 实现具体的恢复逻辑
            }
        }

        free(journal_data);
        fclose(journal);

    } while (0);

    xSemaphoreGive(protection->protection_mutex);
    return ret;
}



// storage_power_protection.c
#include <string.h>
#include "esp_log.h"
#include "storage_power_protection.h"

static const char *TAG = "storage_power";

static esp_err_t write_transaction_log(file_system_t *fs, const char *path,
                                    const void *data, size_t size) {
   char log_path[FILE_PATH_MAX];
   snprintf(log_path, sizeof(log_path), "%s%s", fs->config.base_path, TRANSACTION_PATH);
   
   FILE *f = fopen(log_path, "wb");
   if (!f) {
       ESP_LOGE(TAG, "Failed to open transaction log");
       return ESP_FAIL;
   }

   transaction_header_t header = {
       .magic = TRANSACTION_MAGIC,
       .sequence = fs->transaction->header.sequence + 1,
       .status = TRANSACTION_STARTED,
       .data_size = size
   };
   
   // Calculate CRC32 of data
   esp_err_t ret = fs_calc_crc32(data, size, &header.checksum);
   if (ret != ESP_OK) {
       fclose(f);
       return ret;
   }

   strncpy(header.path, path, sizeof(header.path) - 1);
   
   // Write header
   if (fwrite(&header, sizeof(header), 1, f) != 1) {
       fclose(f);
       return ESP_FAIL;
   }
   
   // Write data
   if (fwrite(data, 1, size, f) != size) {
       fclose(f);
       return ESP_FAIL; 
   }

   fclose(f);
   return ESP_OK;
}

esp_err_t fs_transaction_begin(file_system_t *fs) {
   if (!fs || !fs->transaction) {
       return ESP_ERR_INVALID_ARG;
   }

   xSemaphoreTake(fs->mutex, portMAX_DELAY);
   
   // Reset transaction state
   fs->transaction->in_progress = true;
   fs->transaction->header.status = TRANSACTION_STARTED;
   
   xSemaphoreGive(fs->mutex);
   
   return ESP_OK;
}

esp_err_t fs_transaction_commit(file_system_t *fs) {
   if (!fs || !fs->transaction || !fs->transaction->in_progress) {
       return ESP_ERR_INVALID_ARG;
   }

   esp_err_t ret = ESP_OK;
   char log_path[FILE_PATH_MAX];
   snprintf(log_path, sizeof(log_path), "%s%s", fs->config.base_path, TRANSACTION_PATH);

   xSemaphoreTake(fs->mutex, portMAX_DELAY);

   do {
       // Update transaction status
       fs->transaction->header.status = TRANSACTION_COMMITTED;
       
       // Write updated header
       FILE *f = fopen(log_path, "r+b");
       if (!f) {
           ret = ESP_FAIL;
           break;
       }
       
       if (fwrite(&fs->transaction->header, sizeof(transaction_header_t), 1, f) != 1) {
           fclose(f);
           ret = ESP_FAIL;
           break;
       }
       fclose(f);

       // Clear transaction state
       fs->transaction->in_progress = false;
       
   } while(0);
   
   xSemaphoreGive(fs->mutex);
   return ret;
}

esp_err_t fs_power_fail_recover(file_system_t *fs) {
   if (!fs) {
       return ESP_ERR_INVALID_ARG;
   }

   char log_path[FILE_PATH_MAX];
   snprintf(log_path, sizeof(log_path), "%s%s", fs->config.base_path, TRANSACTION_PATH);

   FILE *f = fopen(log_path, "rb");
   if (!f) {
       return ESP_OK; // No recovery needed
   }

   transaction_header_t header;
   if (fread(&header, sizeof(header), 1, f) != 1) {
       fclose(f);
       return ESP_FAIL;
   }

   if (header.magic != TRANSACTION_MAGIC) {
       fclose(f);
       return ESP_FAIL;
   }

   if (header.status == TRANSACTION_STARTED) {
       // Allocate recovery buffer
       void *data = malloc(header.data_size);
       if (!data) {
           fclose(f);
           return ESP_ERR_NO_MEM;
       }

       // Read transaction data
       if (fread(data, 1, header.data_size, f) != header.data_size) {
           free(data);
           fclose(f);
           return ESP_FAIL;
       }

       // Verify checksum
       uint32_t crc;
       esp_err_t ret = fs_calc_crc32(data, header.data_size, &crc);
       if (ret != ESP_OK || crc != header.checksum) {
           free(data);
           fclose(f);
           return ESP_FAIL;
       }

       // Restore file
       ret = file_system_write(fs, header.path, data, header.data_size);
       
       free(data);
       fclose(f);
       return ret;
   }

   fclose(f);
   return ESP_OK;
}


// src/components/async/storage_async.c
#include <string.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "storage.h"

static const char *TAG = "storage_async";

// 异步写入任务
void async_write_task(void *arg) {
    async_operation_t *op = (async_operation_t *)arg;
    file_system_t *fs = op->context;
    
    esp_err_t ret = file_system_write(fs, op->path, op->buffer, op->size);
    
    op->state = (ret == ESP_OK) ? ASYNC_STATE_COMPLETED : ASYNC_STATE_ERROR;
    if (op->callback) {
        op->callback(fs, ret);
    }
    
    free(op->buffer);
    free(op);
    vTaskDelete(NULL);
}

esp_err_t async_write(file_system_t *fs, const char *path, const void *data, 
                     size_t size, async_callback_t callback, void *context) {
    
    async_operation_t *op = calloc(1, sizeof(async_operation_t));
    if (!op) {
        return ESP_ERR_NO_MEM;
    }
    
    op->path = strdup(path);
    op->buffer = malloc(size);
    if (!op->path || !op->buffer) {
        free(op->path);
        free(op->buffer);
        free(op);
        return ESP_ERR_NO_MEM;  
    }
    memcpy(op->buffer, data, size);
    
    op->size = size;
    op->state = ASYNC_STATE_IN_PROGRESS;
    op->callback = callback;
    op->context = context;
    
    BaseType_t ret = xTaskCreate(async_write_task, "async_write", 4096, op, 5, &op->task);
    if (ret != pdPASS) {
        free(op->path);
        free(op->buffer);
        free(op);
        return ESP_ERR_NO_MEM;
    }
    
    return ESP_OK;
}

// 异步读取任务
void async_read_task(void *arg) {
    async_operation_t *op = (async_operation_t *)arg;
    file_system_t *fs = op->context;
    
    size_t read_size;
    esp_err_t ret = file_system_read(fs, op->path, op->buffer, op->size, &read_size);
    
    op->state = (ret == ESP_OK) ? ASYNC_STATE_COMPLETED : ASYNC_STATE_ERROR;
    if (op->callback) {
        op->callback(fs, ret);
    }
    
    free(op->buffer);
    free(op);
    vTaskDelete(NULL);
}


esp_err_t async_read(file_system_t *fs, const char *path, void *data, 
                    size_t size, async_callback_t callback, void *context) {

    async_operation_t *op = calloc(1, sizeof(async_operation_t)); 
    if (!op) {
        return ESP_ERR_NO_MEM;
    }
    
    op->path = strdup(path);
    op->buffer = data;
    op->size = size;
    op->state = ASYNC_STATE_IN_PROGRESS;  
    op->callback = callback;
    op->context = context;
    
    BaseType_t ret = xTaskCreate(async_read_task, "async_read", 4096, op, 5, &op->task);
    if (ret != pdPASS) {
        free(op);
        return ESP_ERR_NO_MEM;
    }
    
    return ESP_OK;
}


esp_err_t async_cancel(file_system_t *fs, const char *path) {
    if (!fs || !path) {
        return ESP_ERR_INVALID_ARG;
    }
    
    char full_path[FILE_PATH_MAX];
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);
    
    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    for (int i = 0; i < MAX_ASYNC_OPERATIONS; i++) {
        async_operation_t *op = &fs->async_ops[i];
        if (op->state == ASYNC_STATE_IN_PROGRESS && strcmp(op->path, full_path) == 0) {
            vTaskDelete(op->task);
            op->state = ASYNC_STATE_IDLE;
            free(op->path);
            free(op->buffer);
            xSemaphoreGive(fs->mutex);
            return ESP_OK;
        }
    }
    
    xSemaphoreGive(fs->mutex);
    return ESP_ERR_NOT_FOUND;
}


esp_err_t async_wait(file_system_t *fs, const char *path, TickType_t timeout) {
    if (!fs || !path) {
        return ESP_ERR_INVALID_ARG;
    }
    
    char full_path[FILE_PATH_MAX];
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);
    
    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    for (int i = 0; i < MAX_ASYNC_OPERATIONS; i++) {
        async_operation_t *op = &fs->async_ops[i];
        if (op->state == ASYNC_STATE_IN_PROGRESS && strcmp(op->path, full_path) == 0) {
            xSemaphoreGive(fs->mutex);
            return ulTaskNotifyTake(pdTRUE, timeout) == 0 ? ESP_ERR_TIMEOUT : ESP_OK;
        }
    }
    
    xSemaphoreGive(fs->mutex);
    return ESP_ERR_NOT_FOUND;
}


async_state_t async_get_state(file_system_t *fs, const char *path) {
    if (!fs || !path) {
        return ASYNC_STATE_ERROR;  
    }

    char full_path[FILE_PATH_MAX];
    snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path);
    
    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    for (int i = 0; i < MAX_ASYNC_OPERATIONS; i++) {
        async_operation_t *op = &fs->async_ops[i];
        if (strcmp(op->path, full_path) == 0) {
            async_state_t state = op->state;
            xSemaphoreGive(fs->mutex);
            return state;
        }
    }
    
    xSemaphoreGive(fs->mutex);
    return ASYNC_STATE_IDLE;
}

// src/components/error/storage_error.c
#include <string.h>
#include "esp_log.h"
#include "storage.h"

static const char *TAG = "storage_error";

// 初始化错误处理上下文
esp_err_t fs_error_init(file_system_t *fs) {
    fs_ext_t *fs_ext = calloc(1, sizeof(fs_ext_t));
    if (!fs_ext) {
        return ESP_ERR_NO_MEM;
    }
    
    fs_ext->error_ctx = calloc(1, sizeof(fs_error_ctx_t));
    if (!fs_ext->error_ctx) {
        free(fs_ext);
        return ESP_ERR_NO_MEM;
    }

    fs_ext->error_ctx->error_mutex = xSemaphoreCreateMutex();
    if (!fs_ext->error_ctx->error_mutex) {
        free(fs_ext->error_ctx);
        free(fs_ext);
        return ESP_ERR_NO_MEM;
    }

    fs->ext = fs_ext;
    return ESP_OK;
}

// 清理错误处理上下文
void fs_error_deinit(file_system_t *fs) {
    if (!fs || !fs->ext || !fs->ext->error_ctx) {
        return;
    }

    fs_error_ctx_t *ctx = fs->ext->error_ctx;
    if (ctx->error_mutex) {
        vSemaphoreDelete(ctx->error_mutex);
    }

    free(ctx);
    free(fs->ext);
    fs->ext = NULL;
}

// 记录错误信息
void fs_error_record(file_system_t *fs, fs_error_type_t type, uint32_t code, const char* location) {
    if (!fs || !fs->ext || !fs->ext->error_ctx) {
        return;
    }

    fs_error_ctx_t *ctx = fs->ext->error_ctx;
    xSemaphoreTake(ctx->error_mutex, portMAX_DELAY);

    // 获取下一个错误记录位置(循环缓冲)
    fs_error_info_t *error = &ctx->errors[ctx->error_count % 16];
    
    error->type = type;
    error->code = code;
    error->timestamp = time(NULL);
    error->retry_count = 0;
    
    if (location) {
        strncpy(error->location, location, sizeof(error->location) - 1);
        error->location[sizeof(error->location) - 1] = '\0';
    }

    ctx->error_count++;

    xSemaphoreGive(ctx->error_mutex);

    // 记录错误日志
    ESP_LOGE(TAG, "FS Error: type=%d, code=%d, location=%s", 
             type, code, location ? location : "unknown");
}

// 错误恢复
esp_err_t fs_error_recover(file_system_t *fs, fs_error_type_t type) {
    if (!fs || !fs->ext) {
        return ESP_ERR_INVALID_ARG;
    }

    esp_err_t ret = ESP_OK;

    // 根据错误类型执行恢复
    switch (type) {
        case FS_ERROR_DEVICE_FAIL:
            // 重新初始化存储设备
            ret = fs->config.storage_dev->ops.deinit();
            if (ret == ESP_OK) {
                ret = fs->config.storage_dev->ops.init(&fs->config.storage_dev->config);
            }
            break;

        case FS_ERROR_FS_CORRUPT:
            // 尝试格式化并重新挂载
            ret = file_system_format(fs);
            if (ret == ESP_OK) {
                fs_config_t config = fs->config;
                file_system_deinit(fs);
                ret = file_system_init(fs, &config);
            }
            break;

        case FS_ERROR_DMA_FAIL:
            // 重新初始化DMA系统
            file_system_deinit_dma(fs);
            ret = file_system_init_dma(fs);
            break;

        default:
            ret = ESP_ERR_NOT_SUPPORTED;
            break;
    }

    if (ret == ESP_OK) {
        ESP_LOGI(TAG, "Successfully recovered from error type %d", type);
    } else {
        ESP_LOGE(TAG, "Failed to recover from error type %d, err=%d", type, ret);
    }

    return ret;
}

// 获取最近的错误信息
esp_err_t fs_get_last_error(file_system_t *fs, fs_error_info_t *error) {
    if (!fs || !fs->ext || !fs->ext->error_ctx || !error) {
        return ESP_ERR_INVALID_ARG;
    }

    fs_error_ctx_t *ctx = fs->ext->error_ctx;
    xSemaphoreTake(ctx->error_mutex, portMAX_DELAY);

    if (ctx->error_count > 0) {
        // 获取最近的错误记录
        size_t last_idx = (ctx->error_count - 1) % 16;
        memcpy(error, &ctx->errors[last_idx], sizeof(fs_error_info_t));
    } else {
        // 无错误记录
        error->type = FS_ERROR_NONE;
        error->code = 0;
        error->timestamp = 0;
        error->retry_count = 0;
        error->location[0] = '\0';
    }

    xSemaphoreGive(ctx->error_mutex);
    return ESP_OK;
}


// storage_perf.c
#include <string.h>
#include "esp_log.h"
#include "storage_perf.h"

static const char *TAG = "storage_perf";


esp_err_t fs_enable_prefetch(file_system_t *fs, bool enable) {
    // 检查参数有效性
    if (!fs || !fs->cache) {
        return ESP_ERR_INVALID_ARG;
    }

    // 获取文件系统互斥锁
    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    // 设置预读取标志
    fs->cache->prefetch_enabled = enable;
    
    // 释放互斥锁
    xSemaphoreGive(fs->mutex);

    return ESP_OK;
}

static esp_err_t try_prefetch(file_system_t *fs, const char *path) {
    // 参数检查
    if (!fs || !fs->cache || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    char full_path[FILE_PATH_MAX] = {0};
    esp_err_t ret = ESP_OK;
    uint8_t *buffer = NULL;
    FILE *file = NULL;
    size_t read_size = 0;

    // 检查文件是否已在缓存中
    fs_cache_entry_t *entry = find_cache_entry(fs, path);
    if (entry) {
        // 如果已缓存，更新访问信息
        entry->access_count++;
        entry->last_access = time(NULL);
        return ESP_OK;
    }

    // 构建完整文件路径
    if (snprintf(full_path, sizeof(full_path), "%s%s", fs->config.base_path, path) >= sizeof(full_path)) {
        return ESP_ERR_INVALID_SIZE;
    }

    do {
        // 打开文件
        file = fopen(full_path, "rb");
        if (!file) {
            ESP_LOGE(TAG, "Failed to open file for prefetch: %s", full_path);
            ret = ESP_FAIL;
            break;
        }

        // 分配预读取缓冲区
        buffer = malloc(FS_READ_BUFFER_SIZE);
        if (!buffer) {
            ret = ESP_ERR_NO_MEM;
            break;
        }

        // 读取文件数据
        read_size = fread(buffer, 1, FS_READ_BUFFER_SIZE, file);
        if (read_size == 0 && !feof(file)) {
            ret = ESP_FAIL;
            break;
        }

        // 将数据添加到缓存
        ret = add_to_cache(fs, path, buffer, read_size);
        if (ret != ESP_OK) {
            break;
        }

        // 标记为预读取数据
        entry = find_cache_entry(fs, path);
        if (entry) {
            entry->is_prefetch = true;
            entry->access_count = 1;
            entry->last_access = time(NULL);
        }

    } while (0);

    // 清理资源
    if (file) {
        fclose(file);
    }
    if (buffer) {
        free(buffer);
    }

    return ret;
}


esp_err_t fs_prefetch_file(file_system_t *fs, const char *path) {
    if (!fs || !fs->cache || !path) {
        return ESP_ERR_INVALID_ARG;
    }

    // 获取互斥锁
    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    // 启用预读取并执行预读取操作
    fs->cache->prefetch_enabled = true;
    esp_err_t ret = try_prefetch(fs, path);
    
    // 释放互斥锁
    xSemaphoreGive(fs->mutex);

    return ret;
}


void update_cache_stats(file_system_t *fs, bool is_hit, bool is_write, uint64_t op_time) {
    if (!fs || !fs->cache) {
        return;
    }

    // 更新命中/未命中计数
    if (is_hit) {
        fs->cache->stats.cache_hits++;
    } else {
        fs->cache->stats.cache_misses++;
    }

    // 更新操作时间统计
    if (is_write) {
        fs->cache->stats.total_write_time += op_time;
    } else {
        fs->cache->stats.total_read_time += op_time;
    }
}

void fs_reset_perf_stats(file_system_t *fs) {
    if (!fs || !fs->cache) {
        return;
    }

    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    memset(&fs->cache->stats, 0, sizeof(fs->cache->stats));
    xSemaphoreGive(fs->mutex);
}


esp_err_t fs_get_stats(file_system_t *fs, uint32_t *hits, uint32_t *misses, 
                      uint32_t *flushes, uint64_t *read_time, uint64_t *write_time) {
    if (!fs || !fs->cache) {
        return ESP_ERR_INVALID_ARG;
    }

    xSemaphoreTake(fs->mutex, portMAX_DELAY);
    
    // 复制统计信息到输出参数
    if (hits) *hits = fs->cache->stats.cache_hits;
    if (misses) *misses = fs->cache->stats.cache_misses;
    if (flushes) *flushes = fs->cache->stats.buffer_flushes;
    if (read_time) *read_time = fs->cache->stats.total_read_time;
    if (write_time) *write_time = fs->cache->stats.total_write_time;
    
    xSemaphoreGive(fs->mutex);

    return ESP_OK;
}



